﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

using CSF.BusinessCore.Data;
using Ict.DataAccess;

namespace CSF.BusinessCore.BLL
{
    public abstract class TransactionLogic<TEntity> : LogModifyLogic<TEntity>
        where TEntity : ITransaction
    {
        /// <summary>
        /// 根据Id(主键）读取数据库记录并填充到一个数据类实例
        /// </summary>
        /// <param name="id">交易Id</param>
        /// <returns>数据类实例</returns>
        public TEntity GetOneById(int id)
        {
            var q = from p in DataContext.Select<TEntity>()
                    where p.Id == id
                    select p;
            return q.First();
        }

        /// <summary>
        /// 从数据库中直接删除指定Id的记录
        /// </summary>
        /// <param name="id">交易Id</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteOneById(int id)
        {
            using (Executor exec = DataContext.CreateExecutor())
            {
                return DeleteOneById(id, exec);
            }
        }

        /// <summary>
        /// 删除Id为指定值的一行记录
        /// </summary>
        /// <param name="id">对象Id</param>
        /// <param name="exec">执行器实例</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteOneById(int id, Executor exec)
        {
            int count = base.Delete(p => p.Id == id, exec);
            return count > 0;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DeleteById(IEnumerable<int> ids)
        {
            int result = 0;
            using (Executor exec = DataContext.CreateExecutor())
            {
                try
                {
                    exec.BeginTransaction();
                    foreach (var id in ids)
                    {
                        bool success = DeleteOneById(id, exec);
                        if (success)
                            result++;
                    }
                    exec.CommitTransaction();
                }
                catch (Exception)
                {
                    exec.RollbackTransaction();
                    throw;
                }
            }
            return result;
        }

        /// <summary>
        /// 保存数据对象
        /// </summary>
        /// <param name="t">数据对象实例</param>
        public bool UpdateById(TEntity t, int id)
        {
            if (id <= 0)
                throw new NoIdSpecifiedException();

            int count = base.Update(t, p => p.Id == id);

            return count > 0;
        }
    }
}
